{% extends "layouts/base.html" %}

{% block title %}通知公告管理 - 近视预防干预系统{% endblock %}

{% block content %}
<main class="main-content-container">
  <div class="notification-management-content">
    <div class="page-header">
      <h1><i class="bi bi-bell"></i> 通知公告管理中心</h1>
      <p class="text-muted">管理系统通知、公告和推送消息</p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-6">
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-search"></i></span>
              <input type="text" class="form-control" id="searchInput" placeholder="搜索通知标题或内容...">
            </div>
          </div>
          <div class="col-md-3">
            <select class="form-select" id="typeFilter">
              <option value="">全部类型</option>
              <option value="system">系统通知</option>
              <option value="announcement">公告</option>
              <option value="maintenance">维护通知</option>
              <option value="update">更新通知</option>
            </select>
          </div>
          <div class="col-md-3 text-end">
            <button id="createNotificationBtn" class="btn btn-primary">
              <i class="bi bi-plus-circle"></i> 新建通知
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 通知列表 -->
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-list-ul"></i> 通知列表
        </h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover" id="notificationsTable">
            <thead>
              <tr>
                <th>标题</th>
                <th>类型</th>
                <th>状态</th>
                <th>目标用户</th>
                <th>发送数量</th>
                <th>创建时间</th>
                <th>发送时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <!-- 动态加载内容 -->
            </tbody>
          </table>
        </div>
        
        <!-- 分页器 -->
        <nav aria-label="通知分页" class="mt-3">
          <ul class="pagination justify-content-center" id="pagination">
            <!-- 动态生成分页 -->
          </ul>
        </nav>
      </div>
    </div>
  </div>
</main>

<!-- 新建/编辑通知模态框 -->
<div class="modal fade" id="notificationModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="notificationModalTitle">新建通知</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="notificationForm">
          <input type="hidden" id="notificationId" />
          <div class="mb-3">
            <label for="notificationTitle" class="form-label">通知标题</label>
            <input type="text" class="form-control" id="notificationTitle" required>
          </div>
          <div class="mb-3">
            <label for="notificationType" class="form-label">通知类型</label>
            <select class="form-select" id="notificationType" required>
              <option value="">请选择</option>
              <option value="system">系统通知</option>
              <option value="announcement">公告</option>
              <option value="maintenance">维护通知</option>
              <option value="update">更新通知</option>
            </select>
          </div>
          <div class="mb-3">
            <label for="notificationContent" class="form-label">通知内容</label>
            <textarea class="form-control" id="notificationContent" rows="6" required></textarea>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="targetUsers" class="form-label">目标用户</label>
                <select class="form-select" id="targetUsers" required>
                  <option value="">请选择</option>
                  <option value="all">全部用户</option>
                  <option value="admin">管理员</option>
                  <option value="doctor">医生</option>
                  <option value="parent">家长</option>
                </select>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="priority" class="form-label">优先级</label>
                <select class="form-select" id="priority" required>
                  <option value="normal">普通</option>
                  <option value="high">高</option>
                  <option value="urgent">紧急</option>
                </select>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="sendTime" class="form-label">发送时间</label>
                <input type="datetime-local" class="form-control" id="sendTime">
                <div class="form-text">不填写则立即发送</div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="expireTime" class="form-label">过期时间</label>
                <input type="datetime-local" class="form-control" id="expireTime">
                <div class="form-text">不填写则永不过期</div>
              </div>
            </div>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="pushToMiniProgram">
              <label class="form-check-label" for="pushToMiniProgram">
                同时推送到小程序
              </label>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-outline-primary" id="saveNotificationBtn">保存草稿</button>
        <button type="button" class="btn btn-primary" id="sendNotificationBtn">发送通知</button>
      </div>
    </div>
  </div>
</div>

<!-- 查看通知详情模态框 -->
<div class="modal fade" id="notificationDetailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">通知详情</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" id="notificationDetailContent">
        <!-- 动态加载内容 -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    loadNotifications();
    
    // 绑定事件
    document.getElementById('createNotificationBtn').addEventListener('click', showCreateNotificationModal);
    document.getElementById('saveNotificationBtn').addEventListener('click', saveNotification);
    document.getElementById('sendNotificationBtn').addEventListener('click', sendNotification);
    document.getElementById('searchInput').addEventListener('input', debounce(searchNotifications, 300));
    document.getElementById('typeFilter').addEventListener('change', searchNotifications);
});

// 加载通知列表
function loadNotifications(page = 1) {
    const searchTerm = document.getElementById('searchInput').value;
    const typeFilter = document.getElementById('typeFilter').value;
    
    AuthManager.authenticatedFetch(`/api/admin/notifications?page=${page}&search=${searchTerm}&type=${typeFilter}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderNotificationsTable(data.data.notifications);
                renderPagination(data.data.pagination);
            } else {
                showAlert('加载通知列表失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

// 渲染通知表格
function renderNotificationsTable(notifications) {
    const tbody = document.querySelector('#notificationsTable tbody');
    tbody.innerHTML = '';
    
    notifications.forEach(notification => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${notification.title}</td>
            <td>
                <span class="badge bg-info">${getNotificationTypeText(notification.notification_type)}</span>
            </td>
            <td>
                <span class="badge bg-${getStatusColor(notification.status)}">${getStatusText(notification.status)}</span>
            </td>
            <td>${getTargetUsersText(notification.target_users)}</td>
            <td>
                <span class="badge bg-${notification.sent_count > 0 ? 'success' : 'secondary'}">
                    ${notification.sent_count || 0}人
                </span>
            </td>
            <td>${formatDate(notification.created_at)}</td>
            <td>${notification.sent_at ? formatDate(notification.sent_at) : '-'}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewNotification(${notification.id})" title="查看">
                        <i class="bi bi-eye"></i>
                    </button>
                    ${notification.status === 'draft' ? 
                        `<button class="btn btn-outline-warning" onclick="editNotification(${notification.id})" title="编辑">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-outline-success" onclick="publishNotification(${notification.id})" title="发布">
                            <i class="bi bi-send"></i>
                        </button>` : ''}
                    <button class="btn btn-outline-danger" onclick="deleteNotification(${notification.id})" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 工具函数
function getNotificationTypeText(type) {
    const types = {
        'system': '系统通知',
        'announcement': '公告',
        'maintenance': '维护通知',
        'update': '更新通知'
    };
    return types[type] || type;
}

function getTargetUsersText(target) {
    const targets = {
        'all': '全部用户',
        'admin': '管理员',
        'doctor': '医生',
        'parent': '家长'
    };
    return targets[target] || target;
}

function getStatusText(status) {
    const statuses = {
        'draft': '草稿',
        'published': '已发布',
        'sent': '已发送',
        'read': '已读',
        'unread': '未读'
    };
    return statuses[status] || status;
}

function getStatusColor(status) {
    const colors = {
        'draft': 'secondary',
        'published': 'success',
        'sent': 'primary',
        'read': 'info',
        'unread': 'warning'
    };
    return colors[status] || 'light';
}

// 显示创建通知模态框
function showCreateNotificationModal() {
    clearNotificationForm();
    document.getElementById('notificationModalTitle').textContent = '新建通知';
    document.getElementById('notificationId').value = '';
    document.getElementById('saveNotificationBtn').style.display = 'inline-block';
    document.getElementById('sendNotificationBtn').textContent = '发送通知';
    bootstrap.Modal.getOrCreateInstance(document.getElementById('notificationModal')).show();
}

// 清空表单
function clearNotificationForm() {
    document.getElementById('notificationForm').reset();
    document.getElementById('notificationId').value = '';
}

// 保存通知（草稿）
function saveNotification() {
    const formData = getFormData();
    formData.status = 'draft';  // 明确设置为草稿状态
    
    const notificationId = document.getElementById('notificationId').value;
    
    if (notificationId) {
        // 编辑模式
        AuthManager.authenticatedFetch(`/api/admin/notifications/${notificationId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('草稿保存成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('notificationModal')).hide();
                loadNotifications();
            } else {
                showAlert('保存失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
    } else {
        // 新建模式
        AuthManager.authenticatedFetch('/api/admin/notifications', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('草稿保存成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('notificationModal')).hide();
                loadNotifications();
            } else {
                showAlert('保存失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
    }
}

// 发送通知
function sendNotification() {
    const formData = getFormData();
    formData.status = 'sent';  // 设置为发送状态
    
    const notificationId = document.getElementById('notificationId').value;
    
    if (notificationId) {
        // 编辑模式：先更新再发布
        AuthManager.authenticatedFetch(`/api/admin/notifications/${notificationId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新成功后发布
                return AuthManager.authenticatedFetch(`/api/admin/notifications/${notificationId}/publish`, {
                    method: 'POST'
                });
            } else {
                throw new Error(data.message);
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const sentCount = data.data && data.data.sent_count ? data.data.sent_count : 0;
                showSuccessModal('通知发送成功', `本次通知已成功发送给 ${sentCount} 名用户`);
                bootstrap.Modal.getInstance(document.getElementById('notificationModal')).hide();
                loadNotifications();
            } else {
                showAlert('发布失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
    } else {
        // 新建模式：直接发送
        AuthManager.authenticatedFetch('/api/admin/notifications', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const sentCount = data.data && data.data.total_sent ? data.data.total_sent : 0;
                showSuccessModal('通知发送成功', `本次通知已成功发送给 ${sentCount} 名用户`);
                bootstrap.Modal.getInstance(document.getElementById('notificationModal')).hide();
                loadNotifications();
            } else {
                showAlert('发送失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
    }
}

function getFormData() {
    return {
        title: document.getElementById('notificationTitle').value,
        notification_type: document.getElementById('notificationType').value,
        content: document.getElementById('notificationContent').value,
        target_user_type: document.getElementById('targetUsers').value,
        priority: document.getElementById('priority').value,
        scheduled_at: document.getElementById('sendTime').value,
        expire_at: document.getElementById('expireTime').value,
        push_to_miniprogram: document.getElementById('pushToMiniProgram').checked
    };
}

function searchNotifications() {
    loadNotifications(1);
}

// 其他工具函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function formatDate(dateString) {
    return new Date(dateString).toLocaleDateString('zh-CN');
}

// 分页渲染函数
function renderPagination(pagination) {
    const paginationContainer = document.getElementById('pagination');
    if (!paginationContainer) return;
    
    let html = '<ul class="pagination justify-content-center">';
    
    // 上一页
    html += `<li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="${pagination.has_prev ? `loadNotifications(${pagination.page - 1})` : 'return false'}">上一页</a>
    </li>`;
    
    // 页码
    for (let i = 1; i <= pagination.pages; i++) {
        html += `<li class="page-item ${i === pagination.page ? 'active' : ''}">
            <a class="page-link" href="#" onclick="loadNotifications(${i})">${i}</a>
        </li>`;
    }
    
    // 下一页
    html += `<li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
        <a class="page-link" href="#" onclick="${pagination.has_next ? `loadNotifications(${pagination.page + 1})` : 'return false'}">下一页</a>
    </li>`;
    
    html += '</ul>';
    paginationContainer.innerHTML = html;
}

// 查看通知详情
function viewNotification(id) {
    AuthManager.authenticatedFetch(`/api/admin/notifications/${id}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const notification = data.data;
            // 显示详情模态框
            showNotificationDetail(notification);
        } else {
            showAlert('获取通知详情失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function showNotificationDetail(notification) {
    const content = `
        <div class="row">
            <div class="col-md-12">
                <h6>基本信息</h6>
                <table class="table table-borderless">
                    <tr><td><strong>标题:</strong></td><td>${notification.title}</td></tr>
                    <tr><td><strong>类型:</strong></td><td>${getNotificationTypeText(notification.notification_type)}</td></tr>
                    <tr><td><strong>状态:</strong></td><td><span class="badge bg-${getStatusColor(notification.status)}">${getStatusText(notification.status)}</span></td></tr>
                    <tr><td><strong>目标用户:</strong></td><td>${getTargetUsersText(notification.target_users)}</td></tr>
                    <tr><td><strong>发送数量:</strong></td><td>${notification.sent_count || 0}人</td></tr>
                    <tr><td><strong>优先级:</strong></td><td>${notification.priority}</td></tr>
                    <tr><td><strong>创建时间:</strong></td><td>${formatDate(notification.created_at)}</td></tr>
                    <tr><td><strong>发送时间:</strong></td><td>${notification.sent_at ? formatDate(notification.sent_at) : '未发送'}</td></tr>
                </table>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <h6>通知内容</h6>
                <div class="border p-3" style="background-color: #f8f9fa;">
                    ${notification.content.replace(/\n/g, '<br>')}
                </div>
            </div>
        </div>
    `;
    
    document.getElementById('notificationDetailContent').innerHTML = content;
    bootstrap.Modal.getOrCreateInstance(document.getElementById('notificationDetailModal')).show();
}

// 编辑通知
function editNotification(id) {
    AuthManager.authenticatedFetch(`/api/admin/notifications/${id}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const notification = data.data;
            fillNotificationForm(notification);
            document.getElementById('notificationModalTitle').textContent = '编辑通知';
            document.getElementById('notificationId').value = notification.id;
            document.getElementById('saveNotificationBtn').style.display = 'inline-block';
            document.getElementById('sendNotificationBtn').textContent = '发布通知';
            bootstrap.Modal.getOrCreateInstance(document.getElementById('notificationModal')).show();
        } else {
            showAlert('获取通知信息失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function fillNotificationForm(notification) {
    document.getElementById('notificationTitle').value = notification.title || '';
    document.getElementById('notificationType').value = notification.notification_type || '';
    document.getElementById('notificationContent').value = notification.content || '';
    document.getElementById('targetUsers').value = notification.target_users || '';
    document.getElementById('priority').value = notification.priority || 'normal';
    document.getElementById('pushToMiniProgram').checked = notification.push_to_miniprogram || false;
}

// 发布通知
function publishNotification(id) {
    if (!confirm('确定要发布这个通知吗？')) {
        return;
    }
    
    AuthManager.authenticatedFetch(`/api/admin/notifications/${id}/publish`, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const sentCount = data.data && data.data.sent_count ? data.data.sent_count : 0;
            showSuccessModal('通知发布成功', `本次通知已成功发送给 ${sentCount} 名用户`);
            loadNotifications();
        } else {
            showAlert('发布失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 删除通知
function deleteNotification(id) {
    if (!confirm('确定要删除这个通知吗？')) {
        return;
    }
    
    AuthManager.authenticatedFetch(`/api/admin/notifications/${id}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('通知删除成功', 'success');
            loadNotifications();
        } else {
            showAlert('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

function showAlert(message, type) {
    // 显示提示信息
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    
    // 5秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 显示成功模态框
function showSuccessModal(title, message) {
    // 检查是否已有成功模态框，如果有则移除
    const existingModal = document.getElementById('successModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 创建模态框HTML
    const modalHTML = `
    <div class="modal fade" id="successModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">
                        <i class="bi bi-check-circle-fill me-2"></i>${title}
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <div class="mb-3">
                        <i class="bi bi-check-circle text-success" style="font-size: 3rem;"></i>
                    </div>
                    <p class="mb-0">${message}</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // 添加到页面
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('successModal'));
    modal.show();
    
    // 模态框隐藏后移除元素
    document.getElementById('successModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}
</script>
{% endblock %}
